<template>
    <div class="task-statistics-container">
      <el-row :gutter="20">
        <el-col :span="18">
          <h1 class="page-title">工单统计</h1>
        </el-col>
        <el-col :span="6" class="total-tasks">
            <h4 class="page-title">全部工单数：{{ totalTasks }}</h4>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="(item, index) in statisticsCards" :key="index">
          <el-card class="box-card" :body-style="{ padding: '0px' }">
            <div class="card-content">
              <div class="card-icon" :style="{ backgroundColor: item.color }">
                <i :class="item.icon"></i>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-value">{{ item.value }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="chart-row">
        <el-col :span="24">
          <h2 class="chart-title">工单状态分布</h2>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div ref="pieChartRef" style="height: 400px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div ref="barChartRef" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed } from 'vue';
  import { getTaskStatistics } from '@/api/manage/task';
  import * as echarts from 'echarts';
  
  const statistics = ref([]);
  const pieChartRef = ref(null);
  const barChartRef = ref(null);
  
  const fetchData = async () => {
    try {
      const response = await getTaskStatistics();
      statistics.value = response;
    } catch (error) {
      console.error('Failed to fetch task statistics:', error);
    }
  };
  
  const totalTasks = computed(() => {
    return statistics.value.reduce((sum, item) => sum + (item.type_count || 0), 0);
  });
  
  const taskTypes = [
    { id: 1, title: '待办的工单', color: '#FF6347', icon: 'el-icon-s-order' },
    { id: 2, title: '进行中工单', color: '#0393EA', icon: 'el-icon-s-promotion' },
    { id: 3, title: '已取消工单', color: '#FFD700', icon: 'el-icon-s-release' },
    { id: 4, title: '已完成工单', color: '#32CD32', icon: 'el-icon-s-claim' },
  ];
  
  const statisticsCards = computed(() => {
    return taskTypes.map(type => ({
      ...type,
      value: statistics.value.find(item => item.task_status === type.id)?.type_count || 0
    }));
  });
  
  const initPieChart = () => {
    const chartDom = pieChartRef.value;
    const myChart = echarts.init(chartDom);
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)' // 保留原 tooltip 格式
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: '工单状态',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['50%', '50%'],
                itemStyle: {
                    borderRadius: 0,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center',
                    formatter: function(params) {
                        return `{a|${params.name}}`; 
                    },
                    rich: {
                        a: {
                            color: params => params.color, // 使用对应颜色
                            fontSize: 30,
                            fontWeight: 'bold',
                            lineHeight: 50,
                            textBorderColor: '#001', // 黑色边框
                            textBorderWidth: 7, // 边框宽度
                        }
                    }
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '30',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: statisticsCards.value.map(item => ({
                    value: item.value,
                    name: item.title,
                    itemStyle: { color: item.color }
                }))
            }
        ]
    };
    myChart.setOption(option);
};


const initBarChart = () => {
  const chartDom = barChartRef.value;
  const myChart = echarts.init(chartDom);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const total = totalTasks.value;
        const value = params[0].value;
        const percentage = ((value / total) * 100).toFixed(2);
        return `${params[0].name}<br/>数量: ${value}<br/>占比: ${percentage}%`;
      }
    },
    xAxis: {
      type: 'category',
      data: statisticsCards.value.map(item => item.title),
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: statisticsCards.value.map(item => ({
          value: item.value,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: item.color },
              { offset: 1, color: echarts.color.lift(item.color, -0.2) }
            ])
          }
        })),
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        },
        barWidth: '40%',
        itemStyle: {
          borderRadius: [5, 5, 0, 0]
        }
      }
    ]
  };
  myChart.setOption(option);
};
  
  onMounted(async () => {
    await fetchData();
    initPieChart();
    initBarChart();
  });
  </script>
  
  <style scoped>
  .task-statistics-container {
    padding: 20px;
  }
  
  .page-title {
    margin-bottom: 20px;
    color: #333;
  }
  
  .total-tasks {
    text-align: right;
    font-size: 18px;
    font-weight: bold;
    line-height: 40px;
  }
  
  .box-card {
    margin-bottom: 20px;
    height: 120px; 
  }
  
  .card-content {
    display: flex;
    align-items: center;
    padding: 20px;
  }
  
  .card-icon {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
  }
  
  .card-icon i {
    font-size: 30px;
    color: white;
  }
  
  .card-info {
    flex-grow: 1;
  }
  
  .card-title {
    font-size: 16px;
    color: #666;
    margin-bottom: 5px;
    font-weight: bold;
  }
  
  .card-value {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }
  
  .chart-row {
    margin-top: 20px;
  }
  
  .chart-title {
    margin-bottom: 20px;
    color: #333;
  }
  </style>